import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress' //路由进度条

// 路由进度条关闭加载微调器
NProgress.configure({
  showSpinner: false
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/login.vue')
    },
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/Layout/layout.vue'),
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/home.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/article',
          component: () => import('@/views/Article/article.vue'),
          meta: { title: '健康百科' }
        },
        {
          path: '/notify',
          component: () => import('@/views/Notify/notify.vue'),
          meta: { title: '消息通知' }
        },
        {
          path: '/user',
          component: () => import('@/views/User/user.vue'),
          meta: { title: '个人中心' }
        }
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/patient-page.vue'),
      meta: { title: '家庭档案' }
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/Consult/consult-fast.vue'),
      meta: { title: '极速问诊' }
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/Consult/consult-dep.vue'),
      meta: { title: '选择科室' }
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/Consult/consult-illness.vue'),
      meta: { title: '病情描述' }
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/Consult/consult-pay.vue'),
      meta: { title: '问诊支付' }
    },
    {
      path: '/room',
      component: () => import('@/views/Room/room.vue'),
      meta: { title: '问诊室' }
    }
  ]
})

// 全局前置守卫
router.beforeEach((to) => {
  // 开启路由进度条
  NProgress.start()

  // 获取用户仓库
  const userStore = useUserStore()

  // 设置白名单（免登录）
  const whiteList = ['/login', '/register']

  // 如果没有token并且不在白名单内则需要进行登录
  if (!userStore.user?.token && !whiteList.includes(to.path)) {
    return '/login'
  }
})

// 全局后置路由守卫
router.afterEach((to) => {
  // 关闭路由进度条
  NProgress.done()
  // 设置标题
  document.title = `Sokach问诊-${to.meta.title}` || ''
})

export default router
